package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.digest.MD5;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.reflection.ClassConvertUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.common.util.H5DomainUrlUtils;
import com.ts.api.http.platform.entity.apply.ApiPlatApplyChuanBeiFenQi;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExchangeChuanBeiFenQi;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.platform.entity.RespPlatformNoticeApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5Apply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5DataExchange;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMd5ConvertHandler;
import com.ts.api.module.api.entity.ApiProtocol;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 *  川贝上游全流程文档：
 * 链接: https://apifox.com/apidoc/shared-56df4fce-9b4d-4924-8828-e359c3280b01
 * 访问密码: 123456
 *
 *  @author WJB
 */
@ApiPlan(productId = "8", type = ApiPlanConvertType.PLAT_PHONE_MD5)
public class ApiPlatChuanBeiFenQiPhoneMd5Convert implements ApiPlatformPhoneMd5ConvertHandler {

    private static final String KEY = "3b27ff24e56cae02b7d3805b4a5fd819";
    private static final String CHANNEL_ID = "YYMKSVXEJC";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) {
        ApiPlatDataExchangeChuanBeiFenQi data = new ApiPlatDataExchangeChuanBeiFenQi();
        data.setPhone_md5(apiDataExchangeParameter.getPhoneMd5());
        //  年龄
        data.setAge(ClassConvertUtils.toInt(apiDataExchangeParameter.getAge()));
        //  性别：0 未知；1 男；2 女
        Integer sex = ChooseEq.create()
                .when(apiDataExchangeParameter.getSex(), "1", 2)
                .when(apiDataExchangeParameter.getSex(), "0", 1)
                .end(0);
        data.setGender(sex);
        //  ip
        if (ValidParam.isNotEmpty(apiDataExchangeParameter.getIp())) {
            data.setIp(apiDataExchangeParameter.getIp());
        } else {
            data.setIp("127.0.0.1");
        }
        data.setAddress_code(apiDataExchangeParameter.getAreaCode());
        //  城市名称
        data.setAddress_name(apiDataExchangeParameter.getCity());
        //  学历
        Integer educationAttainment = ChooseEq.create()
                .when(apiDataExchangeParameter.getEducationAttainment(), "1", 1)
                .when(apiDataExchangeParameter.getEducationAttainment(), "2", 1)
                .when(apiDataExchangeParameter.getEducationAttainment(), "3", 1)
                .when(apiDataExchangeParameter.getEducationAttainment(), "4", 1)
                .when(apiDataExchangeParameter.getEducationAttainment(), "5", 2)
                .when(apiDataExchangeParameter.getEducationAttainment(), "6", 2)
                .end(0);
        data.setEducation(educationAttainment);
        //  职业
        Integer career = ChooseEq.create()
                .when(apiDataExchangeParameter.getCareer(), "1", 2)
                .when(apiDataExchangeParameter.getCareer(), "2", 1)
                .when(apiDataExchangeParameter.getCareer(), "3", 3)
                .when(apiDataExchangeParameter.getCareer(), "4", 4)
                .when(apiDataExchangeParameter.getCareer(), "5", 3)
                .end(0);
        data.setVocation(career);
        //  信用情况
        Integer overdue = ChooseEq.create()
                .when(apiDataExchangeParameter.getOverdue(), "1", 3)
                .when(apiDataExchangeParameter.getOverdue(), "2", 1)
                .when(apiDataExchangeParameter.getOverdue(), "3", 2)
                .end(0);
        data.setCredit(overdue);
        data.setLoans(0);
        //  芝麻分
        Integer zhima = ChooseEq.create()
                .when(apiDataExchangeParameter.getSesameCredit(), "1", 2)
                .when(apiDataExchangeParameter.getSesameCredit(), "2", 3)
                .when(apiDataExchangeParameter.getSesameCredit(), "3", 4)
                .when(apiDataExchangeParameter.getSesameCredit(), "4", 5)
                .end(0);
        data.setSesame(zhima);
        //  社保
        Integer socialSecurity = ChooseEq.create()
                .when(apiDataExchangeParameter.getSocialSecurity(), "1", 1)
                .when(apiDataExchangeParameter.getSocialSecurity(), "2", 2)
                .when(apiDataExchangeParameter.getSocialSecurity(), "3", 3)
                .when(apiDataExchangeParameter.getSocialSecurity(), "4", 2)
                .end(0);
        data.setSocial(socialSecurity);
        //  公积金
        Integer providentFund = ChooseEq.create()
                .when(apiDataExchangeParameter.getProvidentFund(), "1", 1)
                .when(apiDataExchangeParameter.getProvidentFund(), "2", 2)
                .when(apiDataExchangeParameter.getProvidentFund(), "3", 3)
                .when(apiDataExchangeParameter.getProvidentFund(), "4", 2)
                .end(0);
        data.setGjj(providentFund);
        //  房产
        Integer house = ChooseEq.create()
                .when(apiDataExchangeParameter.getRealEstateInfo(), "1", 1)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "2", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "3", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "4", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "5", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "6", 2)
                .end(0);
        data.setRoom(house);
        //  车产
        Integer vehicle = ChooseEq.create()
                .when(apiDataExchangeParameter.getCarInfo(), "1", 1)
                .when(apiDataExchangeParameter.getCarInfo(), "2", 2)
                .when(apiDataExchangeParameter.getCarInfo(), "3", 3)
                .when(apiDataExchangeParameter.getCarInfo(), "4", 2)
                .end(0);
        data.setCar(vehicle);
        //  商业保险
        Integer commericalInsurance = ChooseEq.create()
                .when(apiDataExchangeParameter.getInsurancePolicy(), "1", 1)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "2", 2)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "3", 3)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "4", 2)
                .end(0);
        data.setPolicy(commericalInsurance);
        //  信用卡
        Integer creditCard = ChooseEq.create()
                .when(apiDataExchangeParameter.getCreditLimit(), "1", 1)
                .when(apiDataExchangeParameter.getCreditLimit(), "2", 2)
                .when(apiDataExchangeParameter.getCreditLimit(), "3", 2)
                .when(apiDataExchangeParameter.getCreditLimit(), "4", 3)
                .when(apiDataExchangeParameter.getCreditLimit(), "5", 3)
                .when(apiDataExchangeParameter.getCreditLimit(), "6", 2)
                .end(0);
        data.setCredit_card(creditCard);
        //  花呗
        Integer huaBei = ChooseEq.create()
                .when(apiDataExchangeParameter.getHbLimit(), "1", 1)
                .when(apiDataExchangeParameter.getHbLimit(), "2", 2)
                .when(apiDataExchangeParameter.getHbLimit(), "3", 2)
                .when(apiDataExchangeParameter.getHbLimit(), "4", 2)
                .when(apiDataExchangeParameter.getHbLimit(), "5", 2)
                .end(0);
        data.setHuabei(huaBei);
        //  白条
        Integer btLimit = ChooseEq.create()
                .when(apiDataExchangeParameter.getBtLimit(), "1", 1)
                .when(apiDataExchangeParameter.getBtLimit(), "2", 2)
                .when(apiDataExchangeParameter.getBtLimit(), "3", 2)
                .when(apiDataExchangeParameter.getBtLimit(), "4", 2)
                .when(apiDataExchangeParameter.getBtLimit(), "5", 2)
                .end(0);
        data.setBaitiao(btLimit);
        //  贷款额度
        Integer money = ChooseEq.create()
                .when(apiDataExchangeParameter.getLoanAmount(), "1", 30000)
                .when(apiDataExchangeParameter.getLoanAmount(), "2", 50000)
                .when(apiDataExchangeParameter.getLoanAmount(), "3", 100000)
                .when(apiDataExchangeParameter.getLoanAmount(), "4", 200000)
                .end(30000);
        data.setMoney(money);
        //  贷款期限
        data.setPeriods(0);
        data.setLoan_purpose(1);

        AES aes = AES.createEcb(KEY.getBytes());
        String dataStr = aes.encryptToBase64Str(JsonUtils.toJson(data));

        Integer time= ClassConvertUtils.toInt(System.currentTimeMillis() / 1000);

        Map<String, Object> signMap = new LinkedHashMap<>();
        signMap.put("channel_code", CHANNEL_ID);
        signMap.put("time", time);
        signMap.put("content", dataStr);
        signMap.put("key", KEY);
        String signString = MD5.create().digestToHex(ApiPlatChuanBeiFenQiPhoneMd5Convert.join(signMap, "&", "="));

        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("channel_code", CHANNEL_ID);
            newMap.put("content", dataStr);
            newMap.put("time", time);
            newMap.put("sign", signString);
        });
        return JsonUtils.toJson(map);
    }

    public static String join(Map<String, Object> map, String entryDelimiter, String keyValueDelimiter) {
        StringBuilder result = new StringBuilder();
        Set<Map.Entry<String, Object>> entrySet = map.entrySet();

        for (Map.Entry<String, Object> entry : entrySet) {
            if (result.length() > 0) {
                result.append(entryDelimiter); // 添加分隔符
            }
            result.append(entry.getKey()) // 键
                    .append(keyValueDelimiter) // 键值分隔符
                    .append(entry.getValue()); // 值
        }

        return result.toString();
    }

    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) {
        ApiPlatApplyChuanBeiFenQi data = new ApiPlatApplyChuanBeiFenQi();
        data.setName(apiApplyParameter.getUserName());
        data.setPhone_md5(apiApplyParameter.getPhoneMd5());
        data.setPhone(apiApplyParameter.getPhone());
        //  年龄
        data.setAge(ClassConvertUtils.toInt(apiApplyParameter.getAge()));
        //  性别 1男 2女
        Integer sex = ChooseEq.create()
                .when(apiApplyParameter.getSex(), "1", 2)
                .when(apiApplyParameter.getSex(), "0", 1)
                .end(0);
        data.setGender(sex);
        //  ip
        if (ValidParam.isNotEmpty(apiApplyParameter.getIp())) {
            data.setIp(apiApplyParameter.getIp());
        } else {
            data.setIp("127.0.0.1");
        }
        data.setAddress_code(apiApplyParameter.getAreaCode());
        //  城市名称
        data.setAddress_name(apiApplyParameter.getCity());
        //  学历
        Integer educationAttainment = ChooseEq.create()
                .when(apiApplyParameter.getEducationAttainment(), "1", 1)
                .when(apiApplyParameter.getEducationAttainment(), "2", 1)
                .when(apiApplyParameter.getEducationAttainment(), "3", 1)
                .when(apiApplyParameter.getEducationAttainment(), "4", 1)
                .when(apiApplyParameter.getEducationAttainment(), "5", 2)
                .when(apiApplyParameter.getEducationAttainment(), "6", 2)
                .end(0);
        data.setEducation(educationAttainment);
        //  职业
        Integer career = ChooseEq.create()
                .when(apiApplyParameter.getCareer(), "1", 2)
                .when(apiApplyParameter.getCareer(), "2", 1)
                .when(apiApplyParameter.getCareer(), "3", 3)
                .when(apiApplyParameter.getCareer(), "4", 4)
                .when(apiApplyParameter.getCareer(), "5", 3)
                .end(0);
        data.setVocation(career);
        //  信用情况
        Integer overdue = ChooseEq.create()
                .when(apiApplyParameter.getOverdue(), "1", 3)
                .when(apiApplyParameter.getOverdue(), "2", 1)
                .when(apiApplyParameter.getOverdue(), "3", 2)
                .end(0);
        data.setCredit(overdue);
        data.setLoans(0);
        //  芝麻分
        Integer zhima = ChooseEq.create()
                .when(apiApplyParameter.getSesameCredit(), "1", 2)
                .when(apiApplyParameter.getSesameCredit(), "2", 3)
                .when(apiApplyParameter.getSesameCredit(), "3", 4)
                .when(apiApplyParameter.getSesameCredit(), "4", 5)
                .end(0);
        data.setSesame(zhima);
        //  社保
        Integer socialSecurity = ChooseEq.create()
                .when(apiApplyParameter.getSocialSecurity(), "1", 1)
                .when(apiApplyParameter.getSocialSecurity(), "2", 2)
                .when(apiApplyParameter.getSocialSecurity(), "3", 3)
                .when(apiApplyParameter.getSocialSecurity(), "4", 2)
                .end(0);
        data.setSocial(socialSecurity);
        //  公积金
        Integer providentFund = ChooseEq.create()
                .when(apiApplyParameter.getProvidentFund(), "1", 1)
                .when(apiApplyParameter.getProvidentFund(), "2", 2)
                .when(apiApplyParameter.getProvidentFund(), "3", 3)
                .when(apiApplyParameter.getProvidentFund(), "4", 2)
                .end(0);
        data.setGjj(providentFund);
        //  房产
        Integer house = ChooseEq.create()
                .when(apiApplyParameter.getRealEstateInfo(), "1", 1)
                .when(apiApplyParameter.getRealEstateInfo(), "2", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "3", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "4", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "5", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "6", 2)
                .end(0);
        data.setRoom(house);
        //  车产
        Integer vehicle = ChooseEq.create()
                .when(apiApplyParameter.getCarInfo(), "1", 1)
                .when(apiApplyParameter.getCarInfo(), "2", 2)
                .when(apiApplyParameter.getCarInfo(), "3", 3)
                .when(apiApplyParameter.getCarInfo(), "4", 2)
                .end(0);
        data.setCar(vehicle);
        //  商业保险
        Integer commericalInsurance = ChooseEq.create()
                .when(apiApplyParameter.getInsurancePolicy(), "1", 1)
                .when(apiApplyParameter.getInsurancePolicy(), "2", 2)
                .when(apiApplyParameter.getInsurancePolicy(), "3", 3)
                .when(apiApplyParameter.getInsurancePolicy(), "4", 2)
                .end(0);
        data.setPolicy(commericalInsurance);
        //  信用卡
        Integer creditCard = ChooseEq.create()
                .when(apiApplyParameter.getCreditLimit(), "1", 1)
                .when(apiApplyParameter.getCreditLimit(), "2", 2)
                .when(apiApplyParameter.getCreditLimit(), "3", 2)
                .when(apiApplyParameter.getCreditLimit(), "4", 3)
                .when(apiApplyParameter.getCreditLimit(), "5", 3)
                .when(apiApplyParameter.getCreditLimit(), "6", 2)
                .end(0);
        data.setCredit_card(creditCard);
        //  花呗
        Integer huaBei = ChooseEq.create()
                .when(apiApplyParameter.getHbLimit(), "1", 1)
                .when(apiApplyParameter.getHbLimit(), "2", 2)
                .when(apiApplyParameter.getHbLimit(), "3", 2)
                .when(apiApplyParameter.getHbLimit(), "4", 2)
                .when(apiApplyParameter.getHbLimit(), "5", 2)
                .end(0);
        data.setHuabei(huaBei);
        //  白条
        Integer btLimit = ChooseEq.create()
                .when(apiApplyParameter.getBtLimit(), "1", 1)
                .when(apiApplyParameter.getBtLimit(), "2", 2)
                .when(apiApplyParameter.getBtLimit(), "3", 2)
                .when(apiApplyParameter.getBtLimit(), "4", 2)
                .when(apiApplyParameter.getBtLimit(), "5", 2)
                .end(0);
        data.setBaitiao(btLimit);
        //  贷款额度
        Integer money = ChooseEq.create()
                .when(apiApplyParameter.getLoanAmount(), "1", 30000)
                .when(apiApplyParameter.getLoanAmount(), "2", 50000)
                .when(apiApplyParameter.getLoanAmount(), "3", 100000)
                .when(apiApplyParameter.getLoanAmount(), "4", 200000)
                .end(30000);
        data.setMoney(money);
        //  贷款期限
        data.setPeriods(0);
        data.setLoan_purpose(1);

        ApiPlatApplyChuanBeiFenQi.BcAgreement bcAgreement = new ApiPlatApplyChuanBeiFenQi.BcAgreement();
        bcAgreement.setTitle("个人信息授权协议");
        bcAgreement.setUrl(H5DomainUrlUtils.createUserProtocolUrl(apiApplyParameter.getProductPlanId(), apiApplyParameter.getPhoneMd5()));
        List<ApiPlatApplyChuanBeiFenQi.BcAgreement> list = new ArrayList<>();
        list.add(bcAgreement);
        data.setBc_agreement(list);

        AES aes = AES.createEcb(KEY.getBytes());
        String dataStr = aes.encryptToBase64Str(JsonUtils.toJson(data));

        Integer time= ClassConvertUtils.toInt(System.currentTimeMillis() / 1000);

        Map<String, Object> signMap = new LinkedHashMap<>();
        signMap.put("channel_code", CHANNEL_ID);
        signMap.put("time", time);
        signMap.put("content", dataStr);
        signMap.put("key", KEY);
        String signString = MD5.create().digestToHex(ApiPlatChuanBeiFenQiPhoneMd5Convert.join(signMap, "&", "="));

        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("channel_code", CHANNEL_ID);
            newMap.put("content", dataStr);
            newMap.put("time", time);
            newMap.put("sign", signString);
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public RespPlatformPhoneMd5Apply respApply(String respJson) {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 1)) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        return RespPlatformPhoneMd5Apply.ofSuc();
    }

    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        return null;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatus) {
        return Map.of();
    }

    @Override
    public RespPlatformPhoneMd5DataExchange respDataExchange(String respJson) {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 1)) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }

        Object data = jsonObject.get("return_data");
        JSONObject resData = null;
        String dataStr = AES.createEcb(KEY.getBytes()).decryptFromBase64Str(String.valueOf(data));
        resData = JSONObject.parseObject(dataStr);
        JSONArray resProtocolList = resData.getJSONArray("protocol_list");

        String orderId = resData.getString("order_num");
        String url = resData.getString("url");
        BigDecimal price = resData.getBigDecimal("price");
        String companyName = resData.getString("company_name");
        String productName = resData.getString("product_name");
        String logo = resData.getString("logo_url");
        List<ApiProtocol> protocolList = CollUtils.newArrayList(newList -> {
            if (ValidParam.isNotEmpty(resProtocolList)) {
                for (int i = 0; i < resProtocolList.size(); i++) {
                    JSONObject protocolObject = resProtocolList.getJSONObject(i);
                    ApiProtocol protocol = new ApiProtocol();
                    protocol.setProtocolName(protocolObject.getString("title"));
                    protocol.setProtocolUrl(protocolObject.getString("url"));
                    newList.add(protocol);
                }
            }
        });

        RespPlatformPhoneMd5DataExchange result = RespPlatformPhoneMd5DataExchange.ofSuc();

        result.setPrice(price);
        result.setLogoPath(logo);
        result.setApplyId(orderId);
        result.setCallUrl(url);
        result.setDisplayName(companyName);
        result.setProductName(productName);
        result.setProtocolList(protocolList);
        return result;
    }
}
